package com.piece.core.db.aspect;

import com.piece.core.framework.annotation.source.DataSource;
import com.piece.core.db.context.DynamicDataSourceContextHolder;
import com.piece.core.framework.util.string.StringUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import java.lang.reflect.Method;

/**
 * 数据源动态切换
 */
@Aspect
public class DataSourceAspect {

    @Before("@annotation(ds)")
    public void before(JoinPoint point, DataSource ds) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        DataSource dataSource = method.getAnnotation(DataSource.class);
        if (null != dataSource && StringUtil.isNotEmpty(dataSource.value())) {
            DynamicDataSourceContextHolder.setDateSourceType(dataSource.value());
        }
    }

    @After("@annotation(ds)")
    public void restoreDataSource(JoinPoint point, DataSource ds) {
        DynamicDataSourceContextHolder.clearDateSourceType();
    }
}